<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
      :isExportExcel2="true"
      :exportFileName="'防盗码.xlsx'"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="detailHandle">新增</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">防盗码导入</el-button>
      </template>
    </FilterTable>

    <!-- 编辑窗口 -->
    <BaseDialog
      :visible.sync="visibleDrawer"
      :title="title"
      width="30%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <add-security-code v-model="initData" :type="handleType" :rowData="formData" @close="infoClose" />
    </BaseDialog>
    <!-- 选择车型 -->
    <BaseDialog
      title="选择车型"
      :visible.sync="issearch"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <carInfoDlg
        ref="carInfoDlg"
        selectType="single"
        :rowData2="formData2"
        @close="closeTypeCarDialog"
      />
    </BaseDialog>
    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="导入" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="防盗码导入模板.xlsx"
        :importRules="importRules"
        :onComplete="importComplete"
        @close="visibleImportPeij = false"
      />
    </BaseDialog>
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import {getSecurityCode,importSecurityCode} from '@/api/customerService/SecurityCode/securityCodeUpdate/index';
  import addSecurityCode from './addSecurityCode';
  import carInfoDlg from '@/pages/cms-common/model';
  import ExcelImport from '@/components/ExcelImport';

  export default {
    name: "securityCodeUpdate",
    mixins: [dictionary],
    components: {ExcelImport,carInfoDlg,addSecurityCode},
    data() {
      return{
        topFilterList: this.createTopFilterList(),
        columns: this.createTableColumns(),
        fetchApi: getSecurityCode,
        fetchParams: {xhrAbort: true},
        formData2: {},
        issearch: false,
        visibleDrawer: false,
        visibleImportPeij: false,
        handleType: '',
        formData: {},
        title: '',
        initData: {},
        rowSelectData: [],
        importRules: [
          {prop: 'vin', title: 'VIN',
            rule: [
              { required: true, message: 'VIN码不能为空' },
            ]},
          {prop: 'scCode', title: 'SC码',
            rule: [
              { required: true, message: 'SC码不能为空' }
            ]
          },
          {prop: 'skcCode', title: 'SKC码',
            rule: [
              { required: true, message: 'SKC码不能为空' }
            ]
          },
        ]
      };
    },
    created() {
      this.getDictData();
    },
    methods: {
      async getDictData() {
        console.info(this.columns.find(x => x.dataIndex == 'createUserInfo.userName').initialValue)
        this.columns.find(x => x.dataIndex == 'isAbnormal').dictItems = this.createDictList('1004')
      },
      /* 打开导入配件Dialog */
      openimportPjDialog(){
        this.visibleImportPeij = true
      },
      //导入
      async importComplete(datas,callback){
        console.info(datas)
        // const errorData = [] 不需要验证，重复列太多
        // datas.forEach((item, index1) => {
        //   const indexarr = []
        //   datas.forEach((i, index2) => {
        //     if (
        //       i.vin === item.vin &&
        //       index1 !== index2) {
        //       indexarr.push(index2 + 1)
        //     }
        //   })
        //   if (indexarr.length) {
        //     errorData.push({
        //       rownum: index1 + 1,
        //       errormsg: `与第${indexarr.join(',')}行车辆重复`,
        //       addmsg: item.vin
        //     })
        //   }
        // })
        // if (errorData.length) {
        //   callback(errorData)
        // } else {
          importSecurityCode(datas).then(res => {
            if(res.resultCode == 200) {
              if(res.data.status){
                this.visibleImportPeij = false
                this.$notify.success({title: '提示信息', message: '批量导入成功'});
                callback()
                this.infoClose({type :"refresh"})
              }else{
                callback(res.data.errorData)
              }
            } else {
              callback([{errormsg: '服务器运行异常'}])
            }
          })
        // }
      },
      createTopFilterList() {
        return[
          // {
          //   type: 'INPUT',
          //   label: '车型',
          //   fieldName: 'model',
          //   placeholder: '请选择',
          //   readonly:true,
          //   unitRender: () => {
          //     return (
          //       <div>
          //       <el-button slot="append" icon="el-icon-search" onClick={() =>this.openDialog()}></el-button>
          //     <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSelectModel()}></el-button>
          //     </div>
          //   );
          //   }
          // },
          {
            type: 'INPUT',
            label: 'VIN',
            fieldName: 'vin',
            placeholder: '请输入...',
          },
          {
            type: 'SELECT',
            label: '数据是否异常',
            fieldName: 'isAbnormal',
            placeholder: '请选择...',
            itemList: this.createDictList('1004')
          }
        ]
      },
      createTableColumns () {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 70,
            fixed: 'left',
            render: props => {
              return (
                <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'edit')}>
              编辑
              </el-button>
              </div>
            );
            }
          },
          {
            title: 'VIN',
            dataIndex: 'vin',
            sorter: true,
          },
          // {
          //   title: '车型',
          //   dataIndex: 'model',
          //   sorter: true,
          // },
          {
            title: 'SC码',
            dataIndex: 'scCode',
            sorter: true,
          },
          {
            title: 'SKC码',
            dataIndex: 'skcCode',
            sorter: true,
          },
          {
            title: '是否异常',
            dataIndex: 'isAbnormal',
            sorter: true,
          },
          {
            title: '创建人',
            dataIndex: 'createUserInfo.userName',
            sorter: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createdAt',
            dateFormat: 'yyyy-MM-dd HH:mm:ss',
            sorter: true,
          }
        ]
      },
      closeTypeCarDialog(val){
        if(val){
          this.topFilterList.find(item => item.fieldName === 'model').initialValue= val.data[0].modelName;
        }
        this.issearch=false;
      },
      openDialog(type){
        this.issearch = true
      },
      //清空选择车型
      clearSelectModel(){
        this.topFilterList.find(item => item.fieldName === 'model').initialValue='';
      },
      selectChange(val) {
        console.log('val', val);
        if(val.length>0){
          console.info('111')
          this.isOpen=false;
          this.rowSelectData = val;
        } else {
          this.isOpen=true;
          this.rowSelectData = [];
        }
      },
      seacherFun(type){
        this.issearch = true
      },
      detailHandle(type) {
        this.title = '新增';
        this.handleType = 'add';
        this.initData = {
          type: type, // add-edit-show
          id: 1001
        }; //行id
        this.visibleDrawer = true;
      },
      editHandle(row, type) {
        if (type === 'edit') {
          this.title = '编辑';
        }
        this.formData = row;
        console.info(row)
        this.handleType = type;
        this.visibleDrawer = true;
      },
      changeHandle(val) {
        this.isOpen=true;
        this.fetchParams = Object.assign({}, val);
      },
      collapseHandle() {
        this.$nextTick(() => {
          this.BaseTable.EXECUTE_RESET_HEIGHT();
        });
      },
      infoClose(rData) {
        this.visibleDrawer = false;
        console.info(rData)
        if (rData.type === 'refresh') {
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
        // this.fetchParams = { ...this.fetchParams };
      },
    }
  }
</script>

<style scoped>

</style>
